<template>
  <div class="app-container">
    <div class="center-container" v-loading="loading">
      <el-card class="form-container">
        <div slot="header" class="clearfix">
          <span>修改助手配置</span>
        </div>
        <el-form ref="form" :model="form" label-width="120px" label-position="left">
          <!-- 基础信息 -->
          <el-form-item label="助手名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入助手名称"></el-input>
          </el-form-item>

          <!-- 模型配置 -->
          <el-divider content-position="left">模型配置</el-divider>

          <el-form-item label="聊天模型">
            <el-select v-model="form.chatModel" placeholder="请选择聊天模型" style="width: 100%">
              <el-option
                v-for="model in modelList"
                :key="model.value"
                :label="model.name"
                :value="model.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="关联知识库">
            <el-select
              v-model="form.dataSet"
              multiple
              placeholder="请选择知识库"
              style="width: 100%"
              @change="handleDatasetChange">
              <el-option
                v-for="dataset in dataSetList"
                :key="dataset.id"
                :label="dataset.name"
                :value="dataset.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="回答风格">
            <el-select
              v-model="form.dofreedom"
              placeholder="请选择回答风格"
              style="width: 100%"
              @change="changeFreedom">
              <el-option
                v-for="style in freedomList"
                :key="style.value"
                :label="style.name"
                :value="style.value">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 高级参数 -->
          <el-divider content-position="left">高级参数配置</el-divider>

          <el-form-item label="温度 (Temperature)">
            <div class="param-container">
              <el-slider
                v-model="form.temperature"
                :min="0"
                :max="1"
                :step="0.01"
                show-input>
              </el-slider>
<!--              <el-switch-->
<!--                v-model="useTemp"-->
<!--                active-text="启用"-->
<!--                inactive-text="禁用">-->
<!--              </el-switch>-->
            </div>
            <div class="param-description">控制回答的随机性，值越高回答越有创造性</div>
          </el-form-item>

          <el-form-item label="Top P">
            <div class="param-container">
              <el-slider
                v-model="form.topP"
                :min="0"
                :max="1"
                :step="0.01"
                show-input>
              </el-slider>
<!--              <el-switch-->
<!--                v-model="useTopP"-->
<!--                active-text="启用"-->
<!--                inactive-text="禁用">-->
<!--              </el-switch>-->
            </div>
            <div class="param-description">控制回答的多样性，值越低回答越保守</div>
          </el-form-item>

          <el-form-item label="存在惩罚">
            <div class="param-container">
              <el-slider
                v-model="form.presencePenalty"
                :min="0"
                :max="2"
                :step="0.01"
                show-input>
              </el-slider>
<!--              <el-switch-->
<!--                v-model="usePresencePenalty"-->
<!--                active-text="启用"-->
<!--                inactive-text="禁用">-->
<!--              </el-switch>-->
            </div>
            <div class="param-description">惩罚已出现的内容，减少重复</div>
          </el-form-item>

          <el-form-item label="频率惩罚">
            <div class="param-container">
              <el-slider
                v-model="form.frequencyPenalty"
                :min="0"
                :max="2"
                :step="0.01"
                show-input>
              </el-slider>
<!--              <el-switch-->
<!--                v-model="useFrequencyPenalty"-->
<!--                active-text="启用"-->
<!--                inactive-text="禁用">-->
<!--              </el-switch>-->
            </div>
            <div class="param-description">惩罚频繁出现的内容，减少重复</div>
          </el-form-item>

          <el-form-item label="最大Token数">
            <div class="param-container">
              <el-slider
                v-model="form.maxTokens"
                :min="1"
                :max="4000"
                :step="1"
                show-input>
              </el-slider>
<!--              <el-switch-->
<!--                v-model="useMaxTokens"-->
<!--                active-text="启用"-->
<!--                inactive-text="禁用">-->
<!--              </el-switch>-->
            </div>
            <div class="param-description">控制回答的最大长度</div>
          </el-form-item>

          <!-- 检索配置 -->
          <el-divider content-position="left">检索配置</el-divider>

          <el-form-item label="相似度阈值">
            <div class="param-container">
              <el-slider
                v-model="form.similarityThreshold"
                :min="0"
                :max="1"
                :step="0.01"
                show-input>
              </el-slider>
<!--              <el-switch-->
<!--                v-model="useSimilarityThreshold"-->
<!--                active-text="启用"-->
<!--                inactive-text="禁用">-->
<!--              </el-switch>-->
            </div>
            <div class="param-description">设置检索内容的最低相似度</div>
          </el-form-item>

          <el-form-item label="关键词权重">
            <div class="param-container">
              <el-slider
                v-model="form.keywordsSimilarityWeight"
                :min="0"
                :max="1"
                :step="0.01"
                show-input>
              </el-slider>
<!--              <el-switch-->
<!--                v-model="useKeywordsSimilarityWeight"-->
<!--                active-text="启用"-->
<!--                inactive-text="禁用">-->
<!--              </el-switch>-->
            </div>
            <div class="param-description">关键词在相似度计算中的权重</div>
          </el-form-item>

          <el-form-item label="返回结果数 (Top N)">
            <div class="param-container">
              <el-slider
                v-model="form.topN"
                :min="1"
                :max="20"
                :step="1"
                show-input>
              </el-slider>
<!--              <el-switch-->
<!--                v-model="useTopN"-->
<!--                active-text="启用"-->
<!--                inactive-text="禁用">-->
<!--              </el-switch>-->
            </div>
            <div class="param-description">设置返回的相似内容数量</div>
          </el-form-item>

          <!-- 交互配置 -->
          <el-divider content-position="left">交互配置</el-divider>

          <el-form-item label="开场白">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入开场白"
              v-model="form.opener">
            </el-input>
          </el-form-item>

          <el-form-item label="空响应提示">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="当没有检索到内容时的默认响应"
              v-model="form.emptyResponse">
            </el-input>
          </el-form-item>

          <el-form-item label="显示引用来源">
            <el-switch v-model="form.showQuote"></el-switch>
          </el-form-item>
        </el-form>

        <div class="form-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存配置</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { chatEdit, chatList, getDataSetList } from '@/api/rag/rag'

// 固定chatId
const FIXED_CHAT_ID = '85b935a200c411f08fe10242ac120006'

export default {
  name: 'FixedChatConfig',
  data() {
    return {
      loading: false,
      submitting: false,
      chatId: FIXED_CHAT_ID,

      // 模型选项
      modelList: [
        { name: 'deepseek-r1:32b', value: 'deepseek-r1:32b' },
        { name: 'llama3.1:latest', value: 'llama3.1:latest' }
      ],
      dataSetList: [],
      freedomList: [
        { name: '精准', value: 1 },
        { name: '平衡', value: 2 },
        { name: '即兴创作', value: 3 }
      ],

      // 参数开关
      useTemp: true,
      useTopP: true,
      usePresencePenalty: true,
      useFrequencyPenalty: true,
      useMaxTokens: true,
      useSimilarityThreshold: true,
      useKeywordsSimilarityWeight: true,
      useTopN: true,

      // 表单数据
      form: {
        name: '',
        chatModel: 'deepseek-r1:32b',
        dataSet: [],
        dofreedom: 1,
        temperature: 0.1,
        topP: 0.3,
        presencePenalty: 0.2,
        frequencyPenalty: 0.7,
        maxTokens: 512,
        similarityThreshold: 0.2,
        keywordsSimilarityWeight: 0.7,
        topN: 8,
        opener: '你好，我是你的建筑能源大模型助理，有什么可以帮到你的吗？',
        emptyResponse: '抱歉，我没有找到相关问题的答案。',
        showQuote: false
      }
    }
  },

  created() {
    this.getDataSetList()

    this.getChatDetail()

  },
  methods: {
    // 获取知识库列表
    async getDataSetList() {
      try {
        this.loading = true
        const res = await getDataSetList(1, 100)
        this.dataSetList = res.data || []
      } catch (error) {
        console.error('获取知识库列表失败:', error)
        this.$message.error('获取知识库列表失败')
      } finally {
        this.loading = false
      }
    },

    // 获取聊天助手详情
    async getChatDetail() {
      try {
        this.loading = true
        const res = await chatList(1, 10)
        const chat = res.data.find(item => item.id === this.chatId)

        console.log(chat.name)
        if (chat) {
          this.form.name = chat.name || '建筑能源大模型'

          this.form.chatModel = chat.llm?.model_name || 'deepseek-r1:32b'
          this.form.dataSet = chat.dataset_ids || []
          console.log(chat.datasets)

          // LLM 参数
          if (chat.llm) {
            this.form.temperature = chat.llm.temperature || 0.1
            this.form.topP = chat.llm.top_p || 0.3
            this.form.presencePenalty = chat.llm.presence_penalty || 0.2
            this.form.frequencyPenalty = chat.llm.frequency_penalty || 0.7
            this.form.maxTokens = chat.llm.max_tokens || 512

            // 根据参数设置回答风格
            this.setFreedomLevel()
          }

          // Prompt 参数
          if (chat.prompt) {
            this.form.similarityThreshold = chat.prompt.similarity_threshold || 0.2
            this.form.keywordsSimilarityWeight = chat.prompt.keywords_similarity_weight || 0.7
            this.form.topN = chat.prompt.top_n || 8
            this.form.opener = chat.prompt.opener || '你好，我是你的建筑能源大模型助理，有什么可以帮到你的吗？'
            this.form.emptyResponse = chat.prompt.empty_response || '抱歉，我没有找到相关问题的答案。'
            this.form.showQuote = chat.prompt.show_quote || false
          }
        } else {
          this.$message.error('未找到指定的聊天助手')
        }
      } catch (error) {
        console.error('获取聊天助手详情失败:', error)
        this.$message.error('获取聊天助手详情失败')
      } finally {
        this.loading = false
      }
    },

    // 设置回答风格
    setFreedomLevel() {
      const { temperature, topP, frequencyPenalty } = this.form

      if (temperature <= 0.2 && topP <= 0.3 && frequencyPenalty >= 0.6) {
        this.form.dofreedom = 1 // 精准
      } else if (temperature >= 0.7 && topP >= 0.7 && frequencyPenalty <= 0.3) {
        this.form.dofreedom = 3 // 即兴创作
      } else {
        this.form.dofreedom = 2 // 平衡
      }
    },

    // 改变回答风格
    changeFreedom() {
      switch (this.form.dofreedom) {
        case 1: // 精准
          this.form.temperature = 0.1
          this.form.topP = 0.3
          this.form.presencePenalty = 0.4
          this.form.frequencyPenalty = 0.7
          break
        case 2: // 平衡
          this.form.temperature = 0.5
          this.form.topP = 0.5
          this.form.presencePenalty = 0.4
          this.form.frequencyPenalty = 0.7
          break
        case 3: // 即兴创作
          this.form.temperature = 0.9
          this.form.topP = 0.9
          this.form.presencePenalty = 0.4
          this.form.frequencyPenalty = 0.2
          break
      }
    },

    // 处理知识库选择变化
    handleDatasetChange(val) {
      this.form.dataSet = val
    },

    // 提交表单
    async submitForm() {
      try {
        this.submitting = true

        const requestData = {
          name: this.form.name,
          avatar: '',
          dataset_ids: this.form.dataSet,
          llm: {
            model_name: this.form.chatModel,
            temperature: this.useTemp ? this.form.temperature : undefined,
            top_p: this.useTopP ? this.form.topP : undefined,
            presence_penalty: this.usePresencePenalty ? this.form.presencePenalty : undefined,
            frequency_penalty: this.useFrequencyPenalty ? this.form.frequencyPenalty : undefined,
            max_tokens: this.useMaxTokens ? this.form.maxTokens : undefined
          },
          prompt: {
            similarity_threshold: this.useSimilarityThreshold ? this.form.similarityThreshold : undefined,
            keywords_similarity_weight: this.useKeywordsSimilarityWeight ? this.form.keywordsSimilarityWeight : undefined,
            top_n: this.useTopN ? this.form.topN : undefined,
            variables: [{ key: "knowledge", optional: true }],
            empty_response: this.form.emptyResponse,
            opener: this.form.opener,
            show_quote: this.form.showQuote
          }
        }

        // 只进行更新操作
        await chatEdit(this.chatId, requestData)
        this.$message.success('助手配置更新成功')

        // 重新加载最新配置
        this.getChatDetail()
      } catch (error) {
        console.error('保存配置失败:', error)
        this.$message.error('保存配置失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.submitting = false
      }
    },

    // 取消
    cancel() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.center-container {
  display: flex;
  justify-content: center;
}

.form-container {
  width: 800px;
  max-width: 100%;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.param-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.param-container .el-slider {
  flex: 1;
}

.param-description {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.form-footer {
  margin-top: 20px;
  text-align: right;
}

.el-divider {
  margin: 30px 0 20px 0;
}
</style>
